<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>重建二叉树</title>
</head>

<body>
    <script>
        function Node(data, left, right) {
            this.data = data;
            this.left = left;
            this.right = right;
        }

        Node.prototype = {
            show: function() {
                console.log(this.data);
            }
        }

        function reConstructBinaryTree(pre, vin) {
            if (pre.length === 0) {
                return null;
            }
            if (pre.length === 1) {
                return new Node(pre[0]);
            }
            const value = pre[0];
            const index = vin.indexOf(value);
            const vinLeft = vin.slice(0, index);
            const vinRight = vin.slice(index + 1);
            const preLeft = pre.slice(1, index + 1);
            const preRight = pre.slice(index + 1);
            const node = new Node(value)
            node.left = reConstructBinaryTree(preLeft, vinLeft);
            node.right = reConstructBinaryTree(preRight, vinRight);
            return node;
        }

        const pret = [1, 2, 4, 7, 3, 5, 6, 8];
        const int = [4, 7, 2, 1, 5, 3, 8, 6];
        const bt = reConstructBinaryTree(pret, int)
        console.log(bt)
    </script>
</body>

</html>